package com.hngy.xpq.android_practice.http;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.hngy.xpq.android_practice.R;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

public class TcpImage {
    public DatagramSocket socket = null;    //监听套接字
    private String ip = "192.168.43.214";   //服务器IP
    private int port = 12345;               //连接密码
    public String refresh = null;
    public Thread sendThread = null;        //发送线程
    private byte[] Cdata;

    public String Transits (byte[] data) {
        Cdata = data;
        sendThread = new Thread(null , sendWord ,"outputWork");
        sendThread.start();
        //休眠机制:如果未收到服务器传递的数据,就进行累加休眠,如果超过五秒,判断为网络问题,也有可能是服务器问题
        //重要性:花了四个小时，想出的最简单的处理数据延迟的方案
        try {
            for (int i = 0 ; refresh == null ; i++) {
                TimeUnit.MILLISECONDS.sleep(i);
                if (i == 5000) {
                    refresh = "网咯故障!!";
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return refresh;
    }

    private Runnable sendWord = new Runnable() {
        @Override
        public void run() {
            try {
                Socket s = new Socket(ip , port);
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                //Byte类型转换为File-BitmapDrawable
                dos.write(Cdata);
                dos.flush();
                dos.close();
                System.out.println("image发送");
//                DataInputStream dis = new DataInputStream(s.getInputStream());
//                while (true) {
//                    refresh = dis.readUTF();
//                    if (refresh != null) {
//                        System.out.println("返回结果:" + refresh);
//                        dos.close();
//                        dis.close();
//                        break;
//                    }
//                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

}
